<?php namespace App\Controllers\Admin;

use App\App;

class Category extends App {

    private $CategoryModel;

    public function __construct() {
        parent::__construct();
        if (!$this->user) {
            showError("用户尚未登录，请登录后重新打开。", '', '无权限访问');
        }
        $this->CategoryModel=new \App\Models\Category();
    }

    public function index() {
        $this->view->categories = $this->get(0, false);
        $this->view->desc = "类别管理，可以使用拖动";
        $this->view->title = "类别管理";
        $this->render('admin/category/list', "default");
    }

    public function get($id, $ajax = true) {       
        $jsonString = json_encode($this->CategoryModel->get(["parent" => $id]));
        if ($ajax) {
            echo $jsonString;
            return;
        }
        return $jsonString;

    }

    public function save() {
        $name = $this->request->post('name');
        $parent = $this->request->post('parent') ?: 0;

        $category = ['id' => 0, 'name' => $name, 'parent' => $parent];

        $this->CategoryModel->save($category);
        $category['id'] = $this->CategoryModel->insertID();
        $this->showJson($category);
    }

    public function parent() {
        $id = $this->request->post('id');
        $parent = $this->request->post('parent');

        $this->CategoryModel->update(['parent' => $parent], ["id " => $id]);
        echo $CategoryModel->lastQuery();
    }

    public function name() {
        $id = $this->request->post('id');
        $name = $this->request->post('name');

        $this->CategoryModel->update(['name' => $name], ["id " => $id]);
    }

    public function delete($id) {
        $this->CategoryModel->deleteAll($id);
        if ($this->db->error) {
            $this->showJson($this->db->error,"Error");
        } else {
            $this->showJson("成功删除分类及其子分类","Success");
        }
    }

}